package com.xyc.petmallsystem.controller;

import com.xyc.petmallsystem.pojo.Cars;
import com.xyc.petmallsystem.pojo.Cat;
import com.xyc.petmallsystem.pojo.Personal;
import com.xyc.petmallsystem.repository.CarsRepository;
import com.xyc.petmallsystem.repository.CatRepository;
import com.xyc.petmallsystem.repository.PersonalRepository;
import com.xyc.petmallsystem.repository.UserRepository;
import com.xyc.petmallsystem.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

/**
 * @author Joel
 * @date 2021/12/2
 */

@RestController
@RequestMapping("/cars")
public class CarsController {
    @Autowired
    CarsRepository carsRepository;

    @Autowired
    CatRepository catRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    PersonalRepository personalRepository;

    @Autowired
    AlipayService alipayService;

    String orderId = null; // 商品的订单号

    @RequestMapping("/find")
    public List<Cars> find() {
        return carsRepository.findAll();
    }

    /*
    猫咪ID  用户名   将cat_id和用户id添加到购物车
     */
    @PostMapping("/add/{id}/{name}")  // 保存某个用户的一条购物车记录
    public String add(@PathVariable Integer id, @PathVariable String name) {
        System.out.println("添加至购物车   id:" + id + "  用户名:" + name);
        Integer user_id = userRepository.getUserIdByName(name);
        System.out.println("用户名id：" + user_id);
        Cat cat = catRepository.findById(id).get(); // 根据猫咪id获取猫咪全部信息

        Cars cars = new Cars();
        cars.setCat_id(id);
        cars.setUser_id(user_id);
        cars.setCat_count(1);
        cars.setCat_price(cat.getPrice());
        cars.setCat_all_price(cat.getPrice());
        cars.setCat_is_coupon(cat.getIs_coupon());
        carsRepository.save(cars);

        if (cars != null) {
            System.out.println("购物车添加成功");
            return "success";
        } else {
            return "error";
        }
    }

    /*
    根据id返回
     */
    @GetMapping("/findById/{id}")
    public Cars findById(@PathVariable("id") Integer id) {
        return carsRepository.findById(id).get();
    }

    /*
    分页  全部   管理员接口
    */
    @GetMapping("/findPage/{page}/{size}")
    public Page<Cars> findPage(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageRequest pageable = PageRequest.of(page - 1, size);
        return carsRepository.findAll(pageable);
    }

    /*
    删除
     */
    @DeleteMapping("delById/{id}")
    public void delById(@PathVariable("id") Integer id) {
        carsRepository.deleteById(id);
    }

    /*购物车  增加功能*/
    @GetMapping("/addCatCount/{id}")
    public String addCatCount(@PathVariable("id") Integer id) {
        Cars cars = carsRepository.findCatCount(id);
        Integer nowCatCount = cars.getCat_count(); //当前数量
        Integer price = cars.getCat_price(); // 单价
        if (nowCatCount >= 5) {     // 不能超过5
            return "Quantity exceeds upper limit";
        }
        cars.setCat_count(nowCatCount + 1);
        cars.setCat_all_price((nowCatCount + 1) * price);
        System.out.println("购物车 增加1" + "#id:" + id);
        carsRepository.save(cars);
        return "success";

    }

    /*
    购物车 减少功能
     */
    @GetMapping("/reduceCatCount/{id}")
    public String reduceCatCount(@PathVariable("id") Integer id) {
        Cars cars = carsRepository.findCatCount(id);
        Integer nowCatCount = cars.getCat_count();
        Integer price = cars.getCat_price(); // 单价
        if (nowCatCount <= 1) { //判断猫咪数量是否为1，为1就不能减少
            System.out.println("购物车 数量不能为0");
            return "number cannot be 0";
        } else {
            cars.setCat_count(nowCatCount - 1);
            //设置价格
            cars.setCat_all_price((nowCatCount - 1) * price);
            carsRepository.save(cars);

            System.out.println("购物车 减少1" + "#id:" + id);
            return "success";
        }

    }

    /*
    更新数据
     */
    @PutMapping("/update")
    public String update(@RequestBody Cars cars) {
        cars.setCat_all_price(cars.getCat_price() * cars.getCat_count()); // 更新总价
        Cars cars2 = carsRepository.save(cars);
        if (cars2 != null)
            return "success";
        return "error";
    }

    /*
    更新总价
     */
    @GetMapping("/updateAllPrice")
    public void updateAllPrice() {
        List<Cars> carsList = carsRepository.findAll();
        for (Cars cars : carsList) {
            cars.setCat_all_price(cars.getCat_count() * cars.getCat_price());
            carsRepository.save(cars);
        }
        System.out.println("********** cars 总价更新完成 *********");
    }

    /*
    计算购物车总价
     */
    @GetMapping("/total/{loginName}")
    public Integer total_price(@PathVariable("loginName") String loginName) {
        Integer user_id = userRepository.getUserIdByName(loginName); // 获取用户的id
        List<Cars> carsList = carsRepository.getCarsFindById(user_id);
        Integer total = 0;
        for (Cars cars : carsList) {
            total += cars.getCat_all_price();
        }
        System.out.println("购物车总价为:" + total);
        return total;
    }

    /*
    获取指定用户的购物车数量
     */
    @GetMapping("/getCarsCount2/{name}")
    public Integer getCarsCount2(@PathVariable("name") String name) {  // 获取用户的名称
        //根据用户的名称获取用户的id
        Integer id = userRepository.getUserIdByName(name);
        System.out.println("==========================================");
        System.out.println("用户名为:" + name + "的id为:" + id);
        System.out.println("==========================================");
        Integer result = carsRepository.getCarsCount2(id);
        System.out.println("购物车数量为:" + result);
        return result;
    }

    /*
    分页    商城 购物车接口
    */
    @GetMapping("/findPage2/{loginName}")
    public List<Cars> findPage_pet(@PathVariable("loginName") String loginName) {
        Integer user_id = userRepository.getUserIdByName(loginName); // 获取用户的id
        return carsRepository.getCarsFindById(user_id);
    }

    /*
    获取用户的地址，收货人，号码
     */
    @GetMapping("/getInfo/{name}")
    public Personal getInfo(@PathVariable String name) {
        Integer user_id = userRepository.getUserIdByName(name); // 获取用户的id
        return personalRepository.getInfo(user_id); // 获取到个人信息
    }

    /*
    支付金额
     */
    @GetMapping("/pay/{money}")
    public String pay(@PathVariable Integer money, String outTradeNo, String subject, String totalAmount, String tradeNo) {

        Random random = new Random();
        outTradeNo = String.valueOf(System.currentTimeMillis()) + random.nextInt(10000); // 生成随机订单编号
        subject = "items-" + random.nextInt(999999); // 生成随机商品名称
        totalAmount = String.valueOf(money); // 金额

        orderId = outTradeNo;
        System.out.println("\n************************************************");
        System.out.println("商品订单号:" + outTradeNo);
        System.out.println("商品名称:" + subject);
        System.out.println("交易金额:" + totalAmount);
        System.out.println("************************************************\n");

        String content = alipayService.tradeQuery(outTradeNo, "  "); // 问题
        System.out.println("商品订单号:" + outTradeNo + "  json数据:" + content);

        return alipayService.webPagePay(subject, outTradeNo, totalAmount);
        //返回跳转到支付页面

    }

    /*
    返回商品的订单号
     */
    @GetMapping("/getOrderId")
    public String getOrderId() {
        System.out.println("########### 商品订单号为:" + orderId);
        return orderId;
    }

}
